<template>
  <a-card :bordered="false" style="width: 300px; text-align: center">
    <span id="title">添加飞机</span>
    <a-form
      :ref="formRef"
      :model="formState"
      :label-col="{ style: { width: '70px' } }"
    >
      <a-form-item label="航空公司" name="airline">
        <a-select v-model:value="formState.airlineId" placeholder="请选择航空公司">
          <a-select-option v-for="airline in airlineList" :key="airline.id" :value="airline.id">{{ airline.fullName }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="飞机型号" name="model">
        <a-input v-model:value="formState.model" placeholder="请输入飞机型号"></a-input>
      </a-form-item>
      <a-form-item label="飞机容量" name="capacity">
        <a-input-number v-model:value="formState.capacity" placeholder="请输入飞机容量" style="width: 180px;"></a-input-number>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" :loading="loading" @click="executeAddAircraft">创建飞机</a-button>
      </a-form-item>
    </a-form>
  </a-card>
</template>

<script lang="ts" setup>
import { FormInstance, message } from 'ant-design-vue';
import { onBeforeMount, ref } from 'vue';
import { addAircraft, AddAircraftParams, queryAllAirlines } from '../api/aircraftApi';
import { HTTP_STATUS } from '../api/request';
import { useRequest } from 'vue-request';
import emitter from '../utils/mitt';
import { EmitList } from '../utils/emitEnums';

interface AirlineInfo {
  id: number,
  simpleName: string,
  fullName: string,
  logo: string,
  prefix: string
}

const formRef = ref<FormInstance>()
const formState = ref<AddAircraftParams>({} as AddAircraftParams)

const airlineList = ref<AirlineInfo[]>([])

onBeforeMount(() => {
  getAirlineList()
})

async function getAirlineList() {
  try {
    const res = await queryAllAirlines()
    if (res.status == HTTP_STATUS.SUCCESS) {
      airlineList.value = res.data
    }
  } catch (error) {
    console.error(error) 
  }
}

const {
  loading,
  run
} = useRequest(addAircraft,{
  manual: true,
  onSuccess: () => message.success("添加成功")
})

function executeAddAircraft() {
  let data = formState.value
  if (data.airlineId == null) {
    message.warn("请选择航空公司")
    return
  } else if (data.model == null) {
    message.warn("请输入飞机型号")
    return 
  } else if (data.capacity == null) {
    message.warn("请输入飞机容量")
    return
  } else if (data.capacity <=0) {
    message.warn("飞机容量须大于0")
    return
  }
  run(data)
  setTimeout(() => {
    emitter.emit(EmitList.AIRCRAFT_CHANGE)
    formRef.value?.resetFields()
  },1000)
}

</script>

<style lang="scss" scoped>
#title {
  display: inline-block;
  font-weight: bold;
  margin-bottom: 10px;
}

:deep(.ant-card-body) {
  padding-bottom: 0;
}
</style>
